package com.japanesee_learning.until;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Build.VERSION;
import android.util.Log;

public class HttpUtil {
    private static int timeoutMillis = 1000;
    // private static int retryTime = 4;
    public static int respCode;
    public static int respPostCode = -1;
    private static String TAG = "HttpUtil";

    public static byte[] httpGetByte(String url, boolean isAlertTask, int Timeout, int retry)
            throws Exception {
        int size;
        byte[] byteBuffer = new byte[1024];
        HttpURLConnection conn = null;
        InputStream in = null;
        ByteArrayOutputStream resultOut = null;

        for (int i = 0; i < retry; i++) {
            URL urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(timeoutMillis * Timeout);
            conn.setConnectTimeout(timeoutMillis * Timeout);

            if (VERSION.RELEASE.equals("1.6")) {
                String xxx = Build.MODEL;
                String yyy = Build.ID;
                conn.setRequestProperty("User-Agent",
                        "Dalvik/1.2.0 (Linux; U; Android 1.6; ja-jp; " + xxx + " Build/" + yyy
                                + ")");
            }

            try {
                respCode = conn.getResponseCode();
                break;
            } catch (UnknownHostException ue) {
                if (i != retry - 1) {
                    Thread.sleep(3000);
                    conn.disconnect();
                    conn = null;
                    continue;
                } else {
                    Log.i(TAG, "64 line error");
                    throw ue;
                }
            } catch (SocketException se) {
                if (i != retry - 1) {
                    Thread.sleep(3000);
                    conn.disconnect();
                    conn = null;
                    continue;
                } else {
                    Log.i(TAG, "80 line error");
                    throw se;
                }
            } catch (Exception e) {
          
                throw e;
            }
        }

        if (respCode == HttpURLConnection.HTTP_OK) {

            in = conn.getInputStream();
            resultOut = new ByteArrayOutputStream();

            while ((size = in.read(byteBuffer)) != -1) {
                resultOut.write(byteBuffer, 0, size);
            }

            resultOut.close();
            in.close();
            conn.disconnect();
            return resultOut.toByteArray();
        } else {
            return null;
        }
    }

    public static byte[] httpGetByte(String url, int Timeout, int retry) throws Exception {
        int size;
        byte[] byteBuffer = new byte[1024];
        HttpURLConnection conn = null;
        InputStream in = null;
        ByteArrayOutputStream resultOut = null;

        for (int i = 0; i < retry; i++) {
            URL urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(timeoutMillis * Timeout);
            conn.setConnectTimeout(timeoutMillis * Timeout);

            try {
                respCode = conn.getResponseCode();
                break;
            } catch (UnknownHostException ue) {
                if (i != retry - 1) {
                    Thread.sleep(3000);
                    conn.disconnect();
                    conn = null;
                    continue;
                } else {
                    Log.i(TAG, "151 line error");

                    throw ue;
                }
            } catch (SocketException se) {
                if (i != retry - 1) {
                    Thread.sleep(3000);

                    conn.disconnect();
                    conn = null;
                    continue;
                } else {
                    Log.i(TAG, "168 line error");
                    throw se;
                }
            } catch (Exception e) {
                throw e;
            }
        }

        if (respCode == HttpURLConnection.HTTP_OK) {
            in = conn.getInputStream();
            resultOut = new ByteArrayOutputStream();

            while ((size = in.read(byteBuffer)) != -1) {
                resultOut.write(byteBuffer, 0, size);
            }

            resultOut.close();
            in.close();
            conn.disconnect();
            return resultOut.toByteArray();
        } else {
            return null;
        }
    }

    public static String httpGetString(String url, int timeout, int retry) throws Exception {
        byte[] httpData = httpGetByte(url, timeout, retry);
        return new String(httpData);
    }

    public static String httpGetString(String url, boolean isAlertTask, int timeout, int retry)
            throws Exception {
        byte[] httpData = httpGetByte(url, true, timeout, retry);
        return new String(httpData);
    }

    public static String httpPostString(String url, byte[] data, int timeout, int retry)
            throws Exception {
        byte[] httpData = httpPostByte(url, data, timeout, retry);
        return new String(httpData);
    }

    public static byte[] httpPostByte(String url, byte[] bodyData, int Timeout, int retry)
            throws Exception {
        int size;
        byte[] byteBuffer = new byte[1024];
        HttpURLConnection conn = null;
        InputStream in = null;
        OutputStream out = null;
        ByteArrayOutputStream resultOut = null;

        for (int i = 0; i < retry; i++) {
            Log.v(TAG, "loop count i = " + i);
            URL urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod("POST");
            // conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
            conn.setReadTimeout(timeoutMillis * Timeout);
            conn.setConnectTimeout(timeoutMillis * Timeout);
            conn.setDoOutput(true);

            try {
                out = conn.getOutputStream();
                out.write(bodyData);
                out.flush();
                out.close();
                respCode = conn.getResponseCode();
                break;
            }
            catch (UnknownHostException ue) {
            	Log.v(TAG, ue.getLocalizedMessage());
                if (i != retry - 1) {
                    Thread.sleep(3000);
                    conn.disconnect();
                    conn = null;
                    continue;
                }
                else 
                {            
                    throw ue;
                }
            }
            catch (SocketException se) {
            	Log.v(TAG, se.getLocalizedMessage());
                if (i != retry - 1) {
                    Thread.sleep(3000);
                    conn.disconnect();
                    conn = null;
                    continue;
                } 
                else {


                    throw se;
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
        }

        if (respCode == HttpURLConnection.HTTP_OK) {
        	Log.v(TAG, "Connect success");
            in = conn.getInputStream();
            resultOut = new ByteArrayOutputStream();
            while ((size = in.read(byteBuffer)) != -1) {
                resultOut.write(byteBuffer, 0, size);
            }

            resultOut.close();
            in.close();
            conn.disconnect();

            return resultOut.toByteArray();
        }
        else {
            Log.v(TAG, "respCode = " + respCode);
            return null;
        }
    }

    public static void download(String _url, String path) {
        try {
            URL url = new URL(_url);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();
            File file = new File(path);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(path);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....

                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } 
        catch (Exception e) {
        }

    }

    public static boolean checkNetworkStatus(Context _context) {

        final ConnectivityManager connMgr = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable()) {

            return true;
        } 
        else if (mobile.isAvailable()) {
            return true;
        }
        else {
            return false;
        }

    }

}